package com.anjingsi.tools.file;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.List;

/**
 * @program: plat-user
 * @description
 * @author: 安静思
 * @create: 2019-07-09 13:41
 **/
@Slf4j
public class MultipartFileUtils {

    public static MultipartFile[] filesToMultipartFiles(List<File> files) {
        MultipartFile[] multipartFiles = new MultipartFile[files.size()];
        for(int i = 0 ; i < files.size() ; i++){
            try {
                File file = files.get(i);
                FileInputStream fileInputStream = new FileInputStream(file);
                MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                        ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
                multipartFiles[i] = multipartFile;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return multipartFiles;
    }


    public static MultipartFile fileToMultipartFile1(File file) throws IOException {
        // 需要导入commons-fileupload的包
        FileItem fileItem = new DiskFileItem(file.getName(),
                Files.probeContentType(file.toPath()),
                false,file.getName(),
                (int)file.length(),
                file.getParentFile());
        byte[] buffer = new byte[4096];
        int n;
        try (
                InputStream inputStream = new FileInputStream(file);
                OutputStream os = fileItem.getOutputStream()){
                     while ( (n = inputStream.read(buffer,0,4096)) != -1){
                           os.write(buffer,0,n);
                     }
                //也可以用IOUtils.copy(inputStream,os);
                MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                return multipartFile;
        }catch (IOException e){
            log.info(e.getMessage());
            throw new RuntimeException("转换异常");
        }
    }

    public static MultipartFile fileToMultipartFile(File file) {
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
            return multipartFile;
        } catch (IOException e) {
            log.info(e.getMessage());
            throw new RuntimeException("转换异常");
        }
    }

    public static File multipartFileToFile(MultipartFile file, String filePath, String fileNewName) {
        if (file != null) {
            try {
                String fileRealName = file.getOriginalFilename();//获得原始文件名;
                int pointIndex =  fileRealName.lastIndexOf(".");//点号的位置
                String fileSuffix = fileRealName.substring(pointIndex);//截取文件后缀
                String saveFileName = fileNewName.concat(fileSuffix);//新文件完整名（含后缀）
                File path = new File(filePath); //判断文件路径下的文件夹是否存在，不存在则创建
                if (!path.exists()) {
                    path.mkdirs();
                }
                File savedFile = new File(filePath);
                boolean isCreateSuccess = savedFile.createNewFile(); // 是否创建文件成功
                if(isCreateSuccess){      //将文件写入
                    //第一种
                    file.transferTo(savedFile);
                    //第二种
                    savedFile = new File(filePath,saveFileName);
                    // 使用下面的jar包
                    FileUtils.copyInputStreamToFile(file.getInputStream(),savedFile);
                }
                return savedFile;
            } catch (Exception e) {
                log.info(e.getMessage());
                throw new RuntimeException("转换异常");
            }
        }
        return null;
    }
}
